import 'dart:async';
import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';

enum RequestType { get, post, put, delete }

class Request {
  static Dio dio = Dio();

  static Future<dynamic> get({
    required String action,
    Map<String, dynamic>? params,
    Options? options,
  }) async {
    return Request.request(action,
        params: params ?? {}, type: RequestType.get, options: options);
  }

  static Future<dynamic> post({
    required String action,
    Map<String, dynamic>? params,
    Options? options,
  }) async {
    return Request.request(action, data: params ?? {}, options: options);
  }

  static Future<dynamic> put({
    required String action,
    Map<String, dynamic>? params,
    Options? options,
  }) async {
    return Request.request(action,
        data: params ?? {}, type: RequestType.put, options: options);
  }

  static Future<dynamic> delete({
    required String action,
    Map<String, dynamic>? params,
    Options? options,
  }) async {
    return Request.request(action,
        data: params ?? {}, type: RequestType.delete, options: options);
  }

  static Future<dynamic> upload(
      {required String action, Map<String, dynamic>? params}) async {
    FormData formData = FormData.fromMap(params!);
    return Request.request(action, data: formData, type: RequestType.post);
  }

  /// 通用的请求方法
  static Future request(
    String url, {
    BaseOptions? baseOptions,
    RequestType type = RequestType.post,
    Map<String, dynamic>? params,
    dynamic data,
    Options? options,
  }) async {
    LogUtil.e('=============== 请求地址: $url, 类型: $type, 参数: $params, 参数: $data');
    Response response;

    if (null == baseOptions) {
      dio.options = BaseOptions()
        ..connectTimeout = 25000
        ..responseType = ResponseType.json
        ..contentType = ContentType.json.toString();
    }

    try {
      switch (type) {
        case RequestType.post:
          response = await dio.post(url,
              queryParameters: params, data: data, options: options);
          break;
        case RequestType.delete:
          response =
              await dio.delete(url, queryParameters: params, options: options);
          break;
        case RequestType.put:
          response = await dio.put(url,
              queryParameters: params, data: data, options: options);
          break;
        case RequestType.get:
        default:
          response =
              await dio.get(url, queryParameters: params, options: options);
      }
    } on Exception catch (e) {
      print('[uri=$url]exception e=${e.toString()}');
      return null;
    }
    return response.data;
  }
}

class NetworkHelper {}
